package com.haoxin.stream.util

import java.util.Properties
import scala.util.{Failure, Success, Try}

/**
 * @note lj
 * @author luoyiliang  2018-09-24
 */
object ConfManager extends Log {
  private lazy val prop: Properties = open("app.properties")

  private def open(file: String) = {
    val in = Thread.currentThread().getContextClassLoader.getResourceAsStream(file)
    val prop = new Properties()
    Try {
      prop.load(in)
      in.close()
    } match {
      case Success(_) => prop
      case Failure(e) => if (in ne null) in.close()
        logError(s"Load properties file error: $file", e)
        throw e
    }
  }

  private val DEFAULT_INT = 0
  private val DEFAULT_LONG = 0L
  private val DEFAULT_DOUBLE = 0.0D
  private val DEFAULT_BOOLEAN = false


  def getString(key: String): String = prop.getProperty(key)

  def getInt(key: String): Int = {
    Try {
      getString(key).toInt
    } match {
      case Success(i) => i
      case Failure(e) => logError("getInt error.", e)
        DEFAULT_INT
    }
  }

  def getLong(key: String): Long = {
    Try {
      getString(key).toLong
    } match {
      case Success(l) => l
      case Failure(e) => logError("getLong error.", e)
        DEFAULT_LONG
    }
  }

  def getDouble(key: String): Double = {
    Try {
      getString(key).toDouble
    } match {
      case Success(d) => d
      case Failure(e) => logError("getDouble error.", e)
        DEFAULT_DOUBLE
    }
  }

  def getBoolean(key: String): Boolean = {
    Try {
      getString(key).toBoolean
    } match {
      case Success(b) => b
      case Failure(e) => logError("getBoolean error.", e)
        DEFAULT_BOOLEAN
    }
  }

}
